package com.itheima.ydd.controller;

import com.itheima.ydd.commom.R;
import com.itheima.ydd.utils.ImageVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Optional;
import java.util.UUID;

//上传图片
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${ydd.path}")
    private String basePath;

    @PostMapping("/upload")
    public R upload(HttpSession session, MultipartFile file) {

        String originalFilename = file.getOriginalFilename();
        //扩展名获取
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //文件名获取
        String fileName = UUID.randomUUID() + suffix;
        //相对路径配置
        String property = System.getProperty("user.dir");
        String imgDir = property + basePath;


        //获取对象
        File file1 = new File(imgDir);
        if (!file1.exists()) {
            file1.mkdirs();
        }

        //savePath拼凑
        String imgPath = imgDir + "/" + fileName;

        //session域存储,用于添加
        session.setAttribute("imgName", imgPath);

        try {
            //文件存储
            file.transferTo(new File(file1, fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //睡眠一秒,前端图片一闪而过,完美模仿黑马优点达
       /* try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
*/
        //获取mimeType
        String mime = "";
        Optional<MediaType> mediaType = MediaTypeFactory.getMediaType(originalFilename);
        if (mediaType.isPresent()) {
            mime = mediaType.get().toString();
        }

        ImageVo imageVo = new ImageVo("upload/images/" + fileName, originalFilename, mime, file.getSize());

        return R.success("", imageVo);
    }
}
